import React,{PropTyeps} from "react";
import Relay from 'react-relay';
import {message} from 'antd';
import moment from 'moment';
import {type} from 'fly';

import ShowWorkGroupProInfoMutation from '../mutaion/ShowWorkGroupProInfoMutation';

import Header from '../components/View_Header';
import Logic_chartVertical from '../components/Logic_chartVertical';
import Logic_chartYaxis from '../components/Logic_chartYaxis';

import {dateFormat,scrollMove} from '../utils';
import "./style.scss";

export default class FactoryresourceDetails extends React.Component {

    static defaultProps = {};

    constructor(props) {
        super(props);

        let date = new Date();

        let preDate = this.preDate = moment(new Date().setDate(date.getDate() - 45));  //第一次默认选择的时间

        this.state = {
            date:preDate,   //选择的时间
            currentDate:null,   //选择之后计算出的最后时间
            dateArr:[],  // 时间数据数组
            data:null,  // 储存时间
            yAxis:[], // Y轴刻度
            canvasWidth:3720,  //默认两个元素的宽度
            proWorkGroup:{}
        };

        this.MAX_TOTAL_COUNT = 0;  //默认值 (用于计算Y轴最大值)
    }

    httpRequest = ({startDate,endDate},callback)=>{
        Relay.Store.commitUpdate(
            new ShowWorkGroupProInfoMutation({
                enterpriseId:sessionStorage.getItem("enterpriseId"),
                workGroupId:this.propState.workGroupId,
                workShopId:this.propState.workShopId,
                startDate:startDate,
                endDate:endDate
            }),
            {
                onFailure: () => {
                    message.error('请求失败');
                },
                onSuccess: (response) => {

                    let content = response.showWorkGroupProInfo.showWorkGroupProInfo;

                    if(content.errorCode == 0){

                        let data = JSON.parse(content.censusGoodsReports);

                        this.setState({proWorkGroup:content.proWorkGroup});

                        callback && callback(data);
                    }
                }
            }
        );
    };

    //整理时间data格式 [转JSON] [设置画布宽度]
    reDataformat = (data,cb)=>{
        this.MAX_TOTAL_COUNT = data.MAX_TOTAL_COUNT;

        for(let i in data){
            if(!data.hasOwnProperty(i)){ continue; }
            if(i === "MAX_TOTAL_COUNT") { continue; }
            data[i] = JSON.parse(data[i]);
            data[i].proStyleNoModelList = JSON.parse(data[i].proStyleNoModelList);
        }

        this.setState({data});

        cb && cb();
    };

    componentWillMount(){
        const state = this.props.location.state;

        if(!state){ message.error("请以正常方式进入页面"); return; }

        this.propState = state;

        // 第一次计算时间，并请求数据/
        const preDate = this.preDate._d;
        const endDate = new Date(preDate);

        endDate.setMonth(preDate.getMonth()+3);

        this.httpRequest({startDate:dateFormat(preDate),endDate:dateFormat(endDate)},(data)=>{
            this.reDataformat(data);
            this.DatePickerChange(this.preDate);
        });
    };

    // 计算Y轴刻度
    yAxisCalibration(maxValue){
        if(type(maxValue) === "string"){ maxValue = parseInt(maxValue); }
        const AVERAGE = maxValue/4;
        let Arr = [];
        maxValue+=AVERAGE;
        if(type(maxValue) === "number" && maxValue%AVERAGE === 0 ){
            while(1){
                if(Arr && Arr[Arr.length-1] <= 0){ break; }
                Arr.push(maxValue-=AVERAGE)
            }
        }
        return Arr;
    };

    // 日期change更改事件
    DatePickerChange = (date)=>{
        const max = 3; //间隔月数
        const chunkWidth = 40;

        let d = new Date(date._d);
        let d_end = new Date(d);
        let dateArr = [];
        let yAxis = [];

        d_end.setMonth(d.getMonth()+max);

        // 更新时间数组取出90天中的时间列表
        while(1) {
            if (d.valueOf() > d_end.valueOf()) { break;}

            dateArr.push(dateFormat(d));  // dateArr :: ["2017-05-05","2017-05-06"......]

            d.setDate(d.getDate() + 1);  //  自增1天
        }

        if(this.MAX_TOTAL_COUNT){yAxis = this.yAxisCalibration(this.MAX_TOTAL_COUNT);}

        this.httpRequest({startDate:dateFormat(date._d),endDate:dateFormat(d_end)},this.reDataformat);

        this.setState({
            canvasWidth:dateArr.length * chunkWidth,
            date,  //当前选择的开始时间
            dateArr, //本地时间队列
            currentDate:dateFormat(d_end),  //结束显示的时间
            yAxis, //Y轴刻度数组
        },()=>{
            const e = this.refs.yyd_chart;
            const scrollWdith = (e.scrollWidth - e.offsetWidth)/2;

            scrollMove(e,scrollWdith);
        });
    };

    render() {
        const {data,date,dateArr,yAxis,currentDate,canvasWidth,proWorkGroup} = this.state;

        return (<div className="factoryResources">
                <Header
                    date={date}
                    DatePickerChange={this.DatePickerChange}
                    currentDate={currentDate}
                />

                <div className="scheduling_WorkshopHeader">
                    <div data-type="block">
                        {proWorkGroup.workShopName} {proWorkGroup.name}
                    </div>
                    <span>
                        工人数量 : {proWorkGroup.workerNum} 人
                    </span>
                </div>

                <div className="scheduling_WorkshopChart">
                    <div className="Yyd-chart" ref="yyd_chart">
                        <Logic_chartVertical
                            data={data}  //data :: {"2017-05-12":xxx}
                            isSewing={false}  //是否展示于 Sewing 页面
                            canvasWidth={canvasWidth}  //canvasWidth :: number
                            dateArr={dateArr}   // ["2017-5-12"....]
                            MAX_TOTAL_COUNT={this.MAX_TOTAL_COUNT}
                        />
                    </div>

                    {/*竖轴*/}
                    <Logic_chartYaxis
                        yAxis={yAxis}
                    />
                </div>

            </div>
        )
    }
}